package com.example.administrator.music;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLEncoder;

/**
 * Created by Administrator on 2018/4/2.
 */

public class LrcFileDownLoad {
    //歌词API
    public static final String LRC_SEARCH_URL="http://geci.me/api/lyric/";
    //设置请求超时15秒
    private static final int Request_TIMEOUT=15*10000;
    //设置等待数据请求超时时间15秒
    private static final int SO_TIME=15*10000;

    public static String getSongLRCUrl(String path,String songname)throws Exception{
        String url=null;
        String str_json=null;

        //歌词名为空放回null
        if (songname==null){
            return null;
        }
        //编码转换
        String name= URLEncoder.encode(songname,"UTF-8");
        str_json=getHtmlCode(path+name);

        //超时以及其他异常时返回null
        if (str_json==null){
            return null;
        }
        JSONObject jsonObject=new JSONObject(str_json);
        int count=jsonObject.getInt("count");

        //没有歌词时返回null
        if (count==0){
            return null;
        }

        //获取歌词列表，这里只获取第一个歌词的url
        JSONArray jsonArray=jsonObject.getJSONArray("result");
        JSONObject item=jsonArray.getJSONObject(0);
        url=item.getString("lrc");
        return url;
    }

    //该方法用于设置超时时间
    public static HttpClient getHttpClient(){
        BasicHttpParams httpParams=new BasicHttpParams();
        HttpConnectionParams .setConnectionTimeout(httpParams,Request_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParams,SO_TIME);
        HttpClient client=new DefaultHttpClient(httpParams);
        return client;
    }

    //获取网页源码
    public static String getHtmlCode(String path){
        String result=null;
        HttpClient httpClient=getHttpClient();
        HttpGet get=new HttpGet(path);
        try {
            HttpResponse response=httpClient.execute(get);
            if (response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                HttpEntity entity=response.getEntity();
                BufferedReader br=new BufferedReader(new InputStreamReader(entity.getContent(),"utf-8"));
                String line;
                result="";
                while ((line=br.readLine())!=null){
                    result +=line+"\n";
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;

    }
}
